from conf import config
import importlib
from lib.config.settings import settings


class plug_manage:
    def __init__(self, hostname=None):
        self.model = settings.MODEL
        self.hostname = hostname
        self.debug = settings.DEBUG

        if self.model == 'ssh':
            self.ssh_port = settings.SSH_PORT
            self.ssh_username = settings.SSH_USERNAME
            self.ssh_pwd = settings.SSH_PWD

    def parse(self):
        response = {}
        for k, v in config.PLUGIN_DIC.items():
            ret = {'code': 100, 'data': None}  # 制定响应字典
            module_name, class_name = v.rsplit('.', 1)
            m = importlib.import_module(module_name)
            cls = getattr(m, class_name)
            res = cls().process(self.common)  # 对象来调用
            ret['data'] = res
            response[k] = ret
        return response

    def common(self, cmd):
        if self.model == "agent":
            return self.__agent(cmd)
        elif self.model == "ssh":
            return self.__ssh(cmd)
        elif self.model == 'salt-stack':
            return self.__salt(cmd)
        else:
            return '不支持的采集的模式'

    def __agent(self, cmd):
        import subprocess
        return subprocess.getoutput(cmd)  # 获取每一台主机的信息

    def __ssh(self, cmd):
        import paramiko
        ssh = paramiko.SSHClient()  # 生成ssh客户端连接对象
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())  # 允许连接不在know_hosts文件中的主机
        ssh.connect(hostname='10.0.0.51', port=22, username='root', password='1')  # 连接服务器，ip地址，端口，主机名，主机密码
        stdin, stdout, stdress = ssh.exec_command(cmd)  # 执行linux命令
        # stdin:输入的命令  stdout:输出的内容，stdress:
        result = stdout.read()
        result = result.decode('utf-8')
        ssh.close()  # 关闭连接
        return result

    def __salt(self,cmd):
        import subprocess
        res_cmd = "salt '%s' cmd.run '%s'"
        return subprocess.getoutput(res_cmd)
